package com.ledict.casefiling.utils;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class JedisUtils {
    private JedisPool pool;

    public JedisUtils(String ip, int port, String auth) {
        if (null == pool) {
            JedisPoolConfig config = new JedisPoolConfig();
            config.setMaxTotal(500);
            config.setMaxIdle(5);
            config.setMaxWaitMillis(100);
            config.setTestOnBorrow(true);

            pool = new JedisPool(config, ip, port, 2000, auth);
        }
    }

    public JedisUtils(JedisPoolConfig config, String ip, int port, int timeout) {
        if (null == pool) {
            pool = new JedisPool(config, ip, port, timeout, null);
        }
    }

    public JedisUtils(JedisPool pool) {
        if (null == pool) {
            this.pool = pool;
        }
    }

    public String get(String key) {
        Jedis jedis = null;
        String value = null;

        jedis = pool.getResource();
        value = jedis.get(key);

        return value;
    }

    /**
     * 返还到连接池
     *
     * @param pool
     * @param jedis
     */
    public static void returnResource(JedisPool pool, Jedis jedis) {
        if (jedis != null) {
            pool.returnResource(jedis);
        }
    }
}
